package spawners {
	import actors.Actor;
	
	import common.ActorMaster;
	import common.Tank;
	
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import interfaces.IDestroyable;
	
	public class GenericSpawner implements IDestroyable {
		protected var _actorMaster:ActorMaster;
		protected var _tank:Tank;
		
		protected var _timer:Timer;
		protected var _type:Class;
		protected var _spawnChance:Number;
		
		private var _destroyed:Boolean;
		
		public function GenericSpawner(typeIn:Class, speed:int, total:int, spawnChanceIn:Number = 1) {
			_actorMaster = ActorMaster.instance;
			_tank = Tank.instance;
			
			_type = typeIn;
			_spawnChance = spawnChanceIn;
			
			//pass in -1 for unlimited spawning
			if (total == -1)
				_timer = new Timer(speed);
			else
				_timer = new Timer(speed, total);
			_timer.addEventListener(TimerEvent.TIMER, spawn);
			_timer.start();
			
			_destroyed = false;
		}
		
		protected function spawn(event:TimerEvent):void {
			if (Math.random() > _spawnChance)
				return;
			
			var actor:Actor = Actor(new _type());
			actor.init();
			
			_actorMaster.addActor(actor);
		}
		
		public function set spawnChance(spawnChanceIn:Number):void {
			_spawnChance = spawnChanceIn;
		}
		
		public function get destroyed():Boolean {
			return _destroyed;
		}
		
		public function destroy():void {
			if (destroyed)
				return;
			_destroyed = true;
			
			_actorMaster = null;
			_tank = null;
			_timer.stop();
			_timer = null;
		}
	}
}
